import re

from django import forms


def data_identity(value):
    if re.search(r'[!@#$%^&*()_+=\[{\]};:<>|./?,-]', value):
        raise forms.ValidationError('不能出现特殊字符')


def username_exist(username, tag='register', table='reader'):
    # 导入模型表
    from author.models import AuthorLogin
    from reader.models import Reader
    from publish.models import PublishAdmin
    # 判断是否存在值
    is_exist_author = AuthorLogin.objects.filter(username=username)
    is_exist_reader = Reader.objects.filter(username=username)
    is_exist_publish = PublishAdmin.objects.filter(username=username)
    # 构建表对应的值
    table2judge = {
        'author': is_exist_author,
        'reader': is_exist_reader,
        'publish': is_exist_publish
    }
    if tag == 'register' and table2judge.get(table):
        raise forms.ValidationError('该用户名已存在')
    elif tag == 'login' and not (table2judge.get(table)):
        raise forms.ValidationError('当前用户不存在')


class LoginForm(forms.Form):
    username = forms.CharField(
        min_length=5,
        label='用户名',
        strip=True,
        # 验证用户名是否合法
        validators=[data_identity, username_exist],
        error_messages={
            'min_length': '用户名最少5位'
        }
    )
    password = forms.CharField(
        min_length=6,
        label='密码',
        strip=True,
        widget=forms.PasswordInput,
        error_messages={
            'min_length': '密码最少6位'
        }
    )
